from common import yaml_util
import pytest
import os
import sys
# sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import requests
import yaml
from common import request_Util
import time
from common import ConnectDataMysql  # 确保导入正确的数据库连接类
from common import get_parentdirectory
from pathlib import Path
#单独存放pytest.fixture()，用于是可以在多个py文件之间共享前置配置。可以有多个，也可以有多个不同层级
#scope=‘作用域’,params='数据驱动',autouse='自动执行',ids=‘自定义参数名’,name=‘重命名’
#作用域function,class,module,package/session

test_util = request_Util.Reqs
# @pytest.fixture(scope='session',autouse=True)
#执行登录操作，获取到token存放到tstyml/extract.yml文件中
@pytest.fixture(scope='module',autouse=True)
def login():
    # print(test_util.__hash__())
    case = yaml_util.Yaml_Util().read_testcase_yaml('testyml/account/admin.yml')
    res = test_util.send_request_and_assert(case, 'testyml/extract.yml')
    try:
        # 尝试解析 JSON 响应
        response_data = res.json()
        # print("解析JSON响应,响应结果为:",response_data)
    except requests.exceptions.JSONDecodeError:
        # 如果响应不是 JSON，打印响应内容
        print("无法解析 JSON，响应内容可能不是 JSON 格式。",res.text)
    except requests.exceptions.RequestException as e:
        # 处理其他可能的请求异常
        print(f"请求出错: {e}")

    #获取token
    token = res.json().get('token')
    headers = {'header': {'Authorization': token, 'accept': '*/*', 'content-type': 'application/json'}}
    # parent_directory = get_parentdirectory.get_parent_directory()
    parent_directory = Path(get_parentdirectory.get_parent_directory())
    # 拼接路径
    # file_path = os.path.join(current_directory, 'testyml' + 'extract.yml')
    # file_path = os.path.join(parent_directory, 'testyml', 'extract.yml')
    file_path = parent_directory / 'testyml' / 'extract.yml'
    print('login()登录amdin账户写入extract的路径',file_path)

    if os.path.exists(file_path):
        with open(file_path, 'r', encoding='utf-8') as f:
            doc = yaml.load(f, Loader=yaml.FullLoader) or {}
        # 检查doc是否为空字典
        if not doc:  # 空字典的真值测试为False
            # 如果doc为空，则将整个headers字典写入YAML文件
            with open(file_path, 'w', encoding='utf-8') as f:
                yaml.dump(headers, f, allow_unicode=True, default_flow_style=False)
                print('headers'  + '插入成功' + {file_path})

        else:
            # 更新或添加 Authorization 字段
            if 'Authorization' not in doc or doc['header']['Authorization'] != token:
                doc['header']['Authorization'] = token
                # 将更新后的字典写回 YAML 文件
                with open(file_path, 'w', encoding='utf-8') as f:
                    yaml.dump(doc, f, allow_unicode=True, default_flow_style=False)
                print(f"Authorization token updated to token in {file_path}")

    else:
        # 如果文件不存在，则直接写入headers字典
        with open(file_path, 'w', encoding='utf-8') as f:
            yaml.dump(headers, f, allow_unicode=True, default_flow_style=False)
        print(f"extract.yml always create,headers updated to {token} in {file_path}")

@pytest.fixture(scope='module')
def db():
    with ConnectDataMysql.ConnectMysql(host='10.51.2.4', user='pvuser', password='XH33tSm1JT0U8Jqt', database='iot_platform') as db:
        yield db

# @pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_call(item):
    start_time = time.time()
    yield
    stop_time = time.time()
    duration = stop_time - start_time
    item.user_properties.append(("duration", duration))
    print(f"\nTest {item.name} took {duration:.4f} seconds")

@pytest.fixture
def update_yaml_files():
    def _update_yaml_files(workPlanId):
        yaml_util.Yaml_Util().modify_testcase_extract('task/cancelTask.yml', 'workPlanId', workPlanId)
        yaml_util.Yaml_Util().modify_testcase_extract('task/processing_baseWorkPlan.yml', 'workPlanId', workPlanId)
        yaml_util.Yaml_Util().modify_testcase_extract('task/get_todoTaskList_id.yml', 'workPlanId', workPlanId)
        yaml_util.Yaml_Util().modify_testcase_extract('task/submit_baseWorkPlan.yml', 'workPlanId', workPlanId)
    return _update_yaml_files


#获取faultid并且写入到yml文件中
@pytest.fixture
def update_faultid():
    """
    Fixture to update multiple YAML files with an ID extracted from a response.
    """

    def _update_faultid():
        try:
            # 读取测试用例 YAML 文件
            case = yaml_util.Yaml_Util().read_testcase_yaml('testyml/faultcode_manage/view_fault_id.yml')

            # 发送请求并获取响应
            res = test_util.send_request_and_assert(case, 'testyml/extract.yml')
            data = res.json()

            # 提取第一个记录的 ID
            first_id = data['data']['records'][0]['id']

            # 更新其他 YAML 文件中的 ID
            yaml_util.Yaml_Util().modify_testcase_extract('faultcode_manage/edit_fault.yml', 'id', first_id)
            yaml_util.Yaml_Util().modify_testcase_extract('faultcode_manage/del_fault.yml', 'id', first_id)
        except Exception as e:
            print(f"Error updating fault ID: {e}")
            raise

    return _update_faultid


# @pytest.fixture(autouse=True)
# def wait_between_tests():
#     yield
#     # 每个测试用例执行后等待 5 秒
#     time.sleep(1.2)

if __name__ == '__main__':
    login()


